﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using mojoPortal.Web.Framework;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using Resources;
using System.Collections;
using ud_Utilities;

namespace mojoPortal.Web.AdminUI
{

    public partial class AdminFeatureSettingsPage : NonCmsBasePage
    {
        private int moduleID = -1;
        Module module = new Module();
        private bool canEdit;
        ArrayList DefaultSettings;
        DBUtilities repository = new DBUtilities();
        private readonly bool useTwoStyleModuleTitle =
            Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseTwoStyleModuleTitle"]);

        void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            SecurityHelper.DisableBrowserCache();
            LoadSettings();
            if (((!WebUser.IsAdminOrContentAdmin) || (!siteSettings.IsServerAdminSite)) && !canEdit)
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }
            PopulateLabels();
            PopulateControls();
        }

        private void PopulateControls()
        {
            if (Page.IsPostBack) return;
            txtRename1.Text = Utilities.RemoveTwoColorModuleTitleText(module.ModuleTitle);
            chkShow.Checked = module.ShowTitle;
            chkHideFromAuth.Checked = module.HideFromAuthenticated;
            chkHideFromUnauth.Checked = module.HideFromUnauthenticated;
            PopulateCustomSettings();
            PopulateListModule(string.Empty);
        }

        private void PopulateListModule(string connectionString)
        {
            //SiteSettings settings = CacheHelper.GetCurrentSiteSettings();
            if (connectionString != string.Empty)
            {
                repository = new DBUtilities(connectionString);
            }
            //ddlListModule.DataSource = repository.GetModuleByModuleGuid(module.FeatureGuid, settings.SiteId);
            ddlListModule.DataSource = repository.GetModuleByModuleGuid(module.FeatureGuid);
            ddlListModule.DataTextField = "ModuleTitle";
            ddlListModule.DataValueField = "ModuleID";
            ddlListModule.DataBind();
            FormatModuleTitle(connectionString);
            if(ddlListModule.Items.Count > 0)
            {
                ddlListModule.Items.Remove(ddlListModule.Items.FindByValue(module.ModuleId.ToString()));
            }
            ddlListModule.Items.Insert(0, new ListItem("No Module", string.Empty));
            ddlListModule.SelectedIndex = 0;
            
        }

        private void FormatModuleTitle(string connectionString)
        {
            if (connectionString != string.Empty)
            {
                repository = new DBUtilities(connectionString);
            }
            foreach (ListItem item in ddlListModule.Items)
            {
                if(item.Text.Contains("</span>"))
                {
                    item.Text = Utilities.RemoveTwoColorModuleTitleText(item.Text);
                }
                //Module m = new Module(Convert.ToInt32(item.Value));
                mp_Modules_SelectOneResult m = repository.GetModule(Convert.ToInt32(item.Value));
                item.Text += @" (Site " + m.SiteID + @")";
            }
        }

        private void PopulateLabels()
        {
            string title = Utilities.RemoveTwoColorModuleTitleText(module.ModuleTitle);
            TitleControl.Header = title;
            Title = SiteUtils.FormatPageTitle(siteSettings, title);
            txtRename2.Visible = useTwoStyleModuleTitle;
            chkReverse.Visible = useTwoStyleModuleTitle;
            lblCurrentName.Text = title;
            ModuleDefinition moduleDefinition = new ModuleDefinition(module.ModuleDefId);
            lblFeatureName.Text
                = ResourceHelper.GetResourceString(
                moduleDefinition.ResourceFile,
                moduleDefinition.FeatureName);
            btnSave.Text = Resource.SaveButton;
        }

        private void PopulateCustomSettings()
        {
            // these are the settings attached to the module instance
            ArrayList customSettingValues = ModuleSettings.GetCustomSettingValues(module.ModuleId);
            foreach (CustomModuleSetting s in DefaultSettings)
            {
                bool found = false;
                foreach (CustomModuleSetting v in customSettingValues)
                {
                    if (v.SettingName == s.SettingName)
                    {
                        found = true;
                    }
                }
                if (!found)
                {
                    ModuleSettings.CreateModuleSetting(
                        module.ModuleGuid,
                        moduleID,
                        s.SettingName,
                        s.SettingValue,
                        s.SettingControlType,
                        s.SettingValidationRegex,
                        s.ControlSrc,
                        s.HelpKey,
                        s.SortOrder);
                }
            }
        }

        private void LoadSettings()
        {
            moduleID = WebUtils.ParseInt32FromQueryString("mid", moduleID);
            module = new Module(moduleID);
            canEdit = WebUser.IsInRoles(module.AuthorizedEditRoles) || WebUser.IsAdminOrContentAdminOrContentPublisher;
            // these are the Settings attached to the Module Definition
            DefaultSettings = ModuleSettings.GetDefaultSettings(module.ModuleDefId);

        }

        #region OnInit

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            btnSave.Click += btnSave_Click;
            btnCheck.Click += btnCheck_Click;
            LoadSideContent(false, false, true, true, 0);
        }

        void btnCheck_Click(object sender, EventArgs e)
        {
            if(txtConnectionString.Text != string.Empty)
            {
                PopulateListModule(txtConnectionString.Text.Trim());
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            ArrayList customSettingValues = ModuleSettings.GetCustomSettingValues(module.ModuleId);
            if (!chkShow.Checked)
            {
                foreach (CustomModuleSetting s in customSettingValues)
                {
                    if (s.SettingName.ToLower().Contains("customcssclasssetting") && !s.SettingValue.Contains("settingsabsolute"))
                    {
                        ModuleSettings.UpdateModuleSetting(module.ModuleGuid, module.ModuleId, s.SettingName, s.SettingValue + " " + "settingsabsolute");
                    }
                }
            }
            else
            {
                foreach (CustomModuleSetting s in customSettingValues)
                {
                    if (s.SettingName.ToLower().Contains("customcssclasssetting") && s.SettingValue.Contains("settingsabsolute"))
                    {
                        ModuleSettings.UpdateModuleSetting(module.ModuleGuid, module.ModuleId, s.SettingName, s.SettingValue.Replace("settingsabsoluteright", "").Replace("settingsabsolute", ""));
                    }
                }
            }
            module.ShowTitle = chkShow.Checked;
            if (txtRename2.Text.Trim() != string.Empty && txtRename1.Text.Trim() != string.Empty)
            {
                string title = chkReverse.Checked
                            ? "<span class='second left'>" + txtRename1.Text.Trim() + "</span>" + "<span class='first right'>" +
                              txtRename2.Text.Trim() + "</span>"
                            : "<span class='first left'>" + txtRename1.Text.Trim() + "</span>" + "<span class='second right'>" +
                              txtRename2.Text.Trim() + "</span>";
                module.ModuleTitle = title;
            }
            else
            {
                module.ModuleTitle = txtRename1.Text.Trim();
            }
            module.HideFromAuthenticated = chkHideFromAuth.Checked;
            module.HideFromUnauthenticated = chkHideFromUnauth.Checked;
            if (scUser.Value.Length > 0)
            {
                try
                {
                    module.EditUserId = int.Parse(scUser.Value);
                }
                catch (ArgumentException) { }
                catch (FormatException) { }
                catch (OverflowException) { }
            }
            else
            {
                module.EditUserId = 0;
            }
            SaveDuplicateModule();
            module.Save();
            WebUtils.SetupRedirect(this, Request.Url.ToString());
        }

        private void SaveDuplicateModule()
        {
            
            if (ddlListModule.SelectedIndex == 0) return;
            string connectionString = txtConnectionString.Text.Trim();
            if (connectionString != string.Empty)
            {
                repository = new DBUtilities(connectionString);
            }
            ArrayList settingValues = ModuleSettings.GetCustomSettingValues(module.ModuleId);
            List<mp_ModuleSettings_SelectResult> duplicateCustomSettingValues = repository.GetCustomSettingValues(Convert.ToInt32(ddlListModule.SelectedValue));
            foreach (CustomModuleSetting s in settingValues)
            {
                foreach (mp_ModuleSettings_SelectResult v in duplicateCustomSettingValues)
                {
                    if (s.SettingName == v.SettingName)
                    {
                        ModuleSettings.UpdateModuleSetting(module.ModuleGuid, module.ModuleId, s.SettingName,
                                                           v.SettingValue);
                    }
                }
            }
        }
        #endregion
    }
}
